package com.code2roc.fastboot.framework.datasource;

import com.code2roc.fastboot.framework.util.StringUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Order(value = 99)
public class DynamicDataSourceAspect {
    private static Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);
    @Autowired
    private DynamicDataSource dynamicDataSource;

    @Pointcut("@annotation(com.code2roc.fastboot.framework.datasource.TargetDataSource) " +
            "|| @within(com.code2roc.fastboot.framework.datasource.TargetDataSource)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Class targetClass = point.getTarget().getClass();
        Method method = signature.getMethod();
        TargetDataSource targetDataSource = (TargetDataSource) targetClass.getAnnotation(TargetDataSource.class);
        boolean needChange = false;
        if (targetDataSource != null) {
            String value = targetDataSource.value();
            if(!StringUtil.isEmpty(value)){
                if (!dynamicDataSource.checkExistDataSource(value)) {
                    throw new DataSourceConfigException("数据源配置不正确");
                }
                needChange = true;
                DataSourceContextHolder.setDataSource(value);
                logger.info("DB切换成功，切换至{}", value);
            }
        }

        try {
            return point.proceed();
        } finally {
            if(needChange){
                logger.info("清除DB切换");
                DataSourceContextHolder.clearDataSource();
            }
        }
    }
}
